# -*- coding: utf-8 -*-

import json
import logging
import traceback

from tablestore import *

from GKModel import OTSHelper
from GKModel import Staff
from utils import build_json


def parse_event(event):
    try:
        evt = json.loads(event)
        headers = evt['headers']
        body = eval(evt['body'])
        account = body['name']
        if account is None or len(account) < 5:
            raise ValueError(1000001, 'Invalid Account')

        password = body['password']
        if password is None or len(password) <= 0:
            raise ValueError(1000002, 'Please Input Password')

        deploy_config = headers['X-Deploy-Config'] \
            if 'X-Deploy-Config' in headers and headers['X-Deploy-Config'] is not None \
            else 'beta'
        return account, password, deploy_config
    except Exception:
        raise ValueError(1000003, 'Please Input UserName and Password')


def handler(event, context):
    logger = logging.getLogger()
    try:
        account, password, deploy_config = parse_event(event)
        ots_client = OTSHelper.create_client()
        staff = Staff.new(ots_client=ots_client, deploy_config=deploy_config, logger=logger)
        account, uid, data = staff.search_staff(account, password)

        tok = staff.update_token(account, uid)

        return build_json(0, 'Success', data, tok)

    except OTSClientError as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(2000001, e.get_error_message(), None)
    except OTSServiceError as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(2000002, e.get_error_message(), None)
    except ValueError as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(e.args[0], e.args[1], None)
    except Exception as e:
        logger.error(e)
        traceback.print_exc()
        return build_json(-1, str(e), None)
